package com.hmyd.hmyd_android.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.adapter.ViewPagerAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Base;
import com.hmyd.hmyd_android.dto.Investment;
import com.hmyd.hmyd_android.dto.Score;
import com.hmyd.hmyd_android.dto.Slide;
import com.hmyd.hmyd_android.ui.HmNoticeActivity;
import com.hmyd.hmyd_android.ui.LatestActivity;
import com.hmyd.hmyd_android.ui.LoginActivity;
import com.hmyd.hmyd_android.ui.PopularEventsActivity;
import com.hmyd.hmyd_android.ui.SignInActivity;
import com.hmyd.hmyd_android.utils.ShakeListenerUtils;
import com.hmyd.hmyd_android.utils.ShakeListenerUtils.ShakeListener;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.ad.AutoGallery;
import com.hmyd.hmyd_android.view.ad.AutoGalleryAdapter;
import com.hmyd.hmyd_android.view.ad.AutoGalleryBase;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 惠民推荐
 * 
 */
public class RecommendationFragment extends BasicFragment implements
OnClickListener, OnPageChangeListener, OnTouchListener {
	private static double rate_hw = 2.1;
	private ViewPagerAdapter mPagerAdapter;
	private AutoGalleryAdapter mAutoGalleryAdapter;
	private ArrayList<AutoGalleryBase> mAdBase = new ArrayList<AutoGalleryBase>();
	private final int ADSILE_ID = 0;// 广告栏
	private final int HOTS_ID = 1;// 推荐项目
	private final int CHECKIN = 3;// 签到
//	private final int GETMYINFO = 4;// 获取用户信息

	// viewpager数据
	private List<Investment> investmentList = new ArrayList<Investment>();

	private View view;
	private AutoGallery mHeadAd;
	private ViewPager mViewPager;
	private LinearLayout dotContent;
	private int pos;
	private View root;
	private RelativeLayout mBtnSignin;
	private RelativeLayout mBtnPop;
	private Button mBtnLatest;
	private RelativeLayout mBtnNotice;
	private ImageView mIvSignin;

	private AnimationDrawable animationDrawable;
//	private View popularevent_redtips;// 红点提示
	private View notice_redtips;
	private View signin_redtips;

	/* 摇一摇签到 --- start --- */
	private SensorManager sensorManager;
	private ShakeListenerUtils shakeListenerUtils;
	private Vibrator vibrator;

	ShakeListener shakeListener = new ShakeListener() {

		@Override
		public void onShakeListener() {
			if (AppBasic.isCheckIned) {
				return;
			}
			
			if (AppBasic.isLogin) {
				vibrator.vibrate(200);
				
				startActivity(new Intent(getActivity(), SignInActivity.class));
			} else {
				startActivity(new Intent(getActivity(), LoginActivity.class));
			}
		}
	};
	/* 摇一摇签到 --- end --- */

	/*BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getBooleanExtra("isAnim", false)) {
				animationDrawable = (AnimationDrawable) mIvSignin
						.getBackground();
				animationDrawable.start();
			}
		}
	};*/

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (root == null) {
			root = inflater.inflate(R.layout.layout_recommendation, container,
					false); // 加载fragment布局
		}
		// ViewUtils.inject(this, view); // 注入view和事件

		// 缓存的rootView需要判断是否已经被加过parent，
		// 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) root.getParent();
		if (parent != null) {
			parent.removeView(root);
		}
		return root;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();

		// 获取幻灯片数据
		onRequest(ADSILE_ID, UrlConstant.AD_SLIDE, HttpMethod.GET, null);
		// 获取热门推荐标数据
		onRequest(HOTS_ID, UrlConstant.HOTS, HttpMethod.GET, null);

//		IntentFilter filter = new IntentFilter("isAnim");
//		getActivity().registerReceiver(receiver, filter);

		shakeListenerUtils = new ShakeListenerUtils(getActivity());
		shakeListenerUtils.setShakeListener(shakeListener);
	}

	@SuppressLint({ "NewApi", "ClickableViewAccessibility" })
	private void initView() {
		view = root.findViewById(R.id.flayout);
		mHeadAd = (AutoGallery) root.findViewById(R.id.Gallery);
		dotContent = (LinearLayout) root.findViewById(R.id.dotcontent);
		mBtnSignin = (RelativeLayout) root.findViewById(R.id.btn_signin);
		mBtnPop = (RelativeLayout) root.findViewById(R.id.btn_popularevent);
		mBtnLatest = (Button) root.findViewById(R.id.btn_latest);
		mBtnNotice = (RelativeLayout) root.findViewById(R.id.btn_notice);
		mIvSignin = (ImageView) root.findViewById(R.id.iv_signin);
//		popularevent_redtips = root.findViewById(R.id.popularevent_redtips);
		notice_redtips = root.findViewById(R.id.notice_redtips);
		signin_redtips = root.findViewById(R.id.signin_redtips);

		mIvSignin.setBackgroundResource(R.anim.sigin);
		animationDrawable = (AnimationDrawable) mIvSignin.getBackground();

		mBtnSignin.setOnClickListener(this);
		mBtnPop.setOnClickListener(this);
		mBtnLatest.setOnClickListener(this);
		mBtnNotice.setOnClickListener(this);

		// 轮播图
		mAutoGalleryAdapter = new AutoGalleryAdapter(getActivity(), mHeadAd,
				mAdBase);

		mHeadAd.setAdapter(mAutoGalleryAdapter);
		mHeadAd.initPointView(getActivity(), view);
		mHeadAd.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if(mAdBase.get(position).QRShare == true){
					Utils.jumpURLS(getActivity(), mAdBase.get(position).mLink,
							mAdBase.get(position).mTitle,
							mAdBase.get(position).mIconUrl, true, true);
				} else if (mAdBase.get(position).QRShare == false) {
					Utils.jumpURL(getActivity(), mAdBase.get(position).mLink,
							mAdBase.get(position).mTitle,
							mAdBase.get(position).mIconUrl, true);
				}
			}
		});

		mHeadAd.setFocusable(true);
		mHeadAd.setOnTouchListener(this);

		RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view
				.getLayoutParams();
		lp.width = Utils.screenWidth_;
		lp.height = (int) (Utils.screenWidth_ / rate_hw);
		view.setLayoutParams(lp);
		FrameLayout.LayoutParams lp1 = (FrameLayout.LayoutParams) mHeadAd
				.getLayoutParams();
		lp1.width = Utils.screenWidth_;
		lp1.height = (int) (Utils.screenWidth_ / rate_hw);
		mHeadAd.setLayoutParams(lp1);


		mViewPager = (ViewPager) root.findViewById(R.id.vp_recommend);
		mViewPager.setOnPageChangeListener(this);

		Intent intent = new Intent("isDrag");
		intent.putExtra("isDrag", true);
		getActivity().sendBroadcast(intent);
		mViewPager.setCurrentItem(0);
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mPagerAdapter != null && mPagerAdapter.mHelper != null) {
			mPagerAdapter.mHelper.start();
		}

		sensorManager = (SensorManager) getActivity().getSystemService(
				Service.SENSOR_SERVICE);
		vibrator = (Vibrator) getActivity().getSystemService(
				Service.VIBRATOR_SERVICE);

		sensorManager.registerListener(shakeListenerUtils,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);

		setCheckined(AppBasic.isCheckIned);
	}
	
	// 首页签到动画
	public void setCheckined(boolean ischeckined){
		if (animationDrawable != null) {
			if (!ischeckined) {
				animationDrawable.start();
				signin_redtips.setVisibility(View.VISIBLE);
				
				return;
			} else {
				animationDrawable.stop();
			}
		} 
		
		mIvSignin.setBackgroundResource(R.drawable.qiandaoicon46);
		signin_redtips.setVisibility(View.GONE);
	}


	@Override
	public void onPause() {
		if (sensorManager != null) {
			sensorManager.unregisterListener(shakeListenerUtils);
		}
		super.onPause();

		if (mPagerAdapter != null && mPagerAdapter.mHelper != null) {
			mPagerAdapter.mHelper.cancel();
		}

		if (animationDrawable != null) {
			animationDrawable.stop();
		}
	}

	@Override
	public void onStop() {
		if (sensorManager != null) {
			sensorManager.unregisterListener(shakeListenerUtils);
		}
		
		if (animationDrawable != null) {
			animationDrawable.stop();
		}
		super.onStop();
	}

	@Override
	public void onDestroyView() {
		if (root != null && root.getParent() != null) {
			((ViewGroup)root.getParent()).removeView(root);
		}
		if (this != null) {
			FragmentManager mManager = getFragmentManager();
			if(mManager != null && !mManager.isDestroyed()){
				final FragmentTransaction mTransaction = mManager.beginTransaction();
				if(mTransaction != null){
					mTransaction.remove(this).commit();
				}
			}
		}
	}

	@SuppressLint({ "InflateParams", "NewApi" })
	@Override
	public void onPostSuccess(int postId, String result) {
		if (TextUtils.isEmpty(result)) {
			return;
		}
		Gson gson = new Gson();
		switch (postId) {
		case ADSILE_ID:
			java.lang.reflect.Type type = new TypeToken<List<Slide>>() {
			}.getType();
			List<Slide> slideList = gson.fromJson(result, type);

			if (slideList != null && slideList.size() > 0) {
				mAdBase.clear();
				for (Slide slide : slideList) {
					AutoGalleryBase itemBase = new AutoGalleryBase();
					itemBase.mUrl = slide.image;
					itemBase.mLink = slide.url;
					itemBase.mTitle = slide.title;
					itemBase.QRShare = slide.QRShare;

					mAdBase.add(itemBase);
				}

				mHeadAd.setAdapter(mAutoGalleryAdapter);
				mAutoGalleryAdapter.notifyDataSetChanged();
			}
			
			break;
		case HOTS_ID:
			java.lang.reflect.Type type2 = new TypeToken<List<Investment>>() {
			}.getType();

			// 清除ViewPager内容
			investmentList.clear();
			mViewPager.removeAllViews();

			investmentList = gson.fromJson(result, type2);

			mPagerAdapter = new ViewPagerAdapter(getActivity(), investmentList);
			mViewPager.setAdapter(mPagerAdapter);

			addDotContent();
			break;
		case CHECKIN:
			java.lang.reflect.Type checkinType = new TypeToken<Base<Score>>() {
			}.getType();
			Base<Score> scoreBase = gson.fromJson(result, checkinType);
			if (scoreBase != null && scoreBase.data != null) {
				AppBasic.totalScore = scoreBase.data.totalScore;
				AppBasic.rewardScore = scoreBase.data.rewardScore;
				AppBasic.nextTimeScore = scoreBase.data.nextTimeScore;
			}
			startActivity(new Intent(getActivity(), SignInActivity.class));
			break;
			/*case GETMYINFO:
			java.lang.reflect.Type typeInfo = new TypeToken<User>() {
			}.getType();
			User user = gson.fromJson(result, typeInfo);
			// 判断是否显示红点
//			if (user.haveNewHotActivity) {
//				popularevent_redtips.setVisibility(View.VISIBLE);
//			} else {
//				popularevent_redtips.setVisibility(View.GONE);
//			}

			if (user.haveNewArticel) {
				notice_redtips.setVisibility(View.VISIBLE);
			} else {
				notice_redtips.setVisibility(View.GONE);
			}
			
			AppBasic.isCheckIned = user.isCheckIned;
			AppBasic.totalScore = user.score;
			setCheckined(AppBasic.isCheckIned);
			break;
*/	
		default:
			break;
		}
	}

	/**
	 * 添加底部圆点
	 */
	private void addDotContent(){
		final LinearLayout.LayoutParams params = new LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		params.setMargins(15, 0, 0, 0);


		for (int i = 0; i < investmentList.size(); i++) {
			ImageView imageView = new ImageView(getActivity());
			imageView.setLayoutParams(params);

			imageView.setBackgroundResource(
					R.drawable.shape_viewpager_dot_nomal);
			dotContent.addView(imageView);
		}

		setDotColor(0);
	}

	/**
	 * 设置圆点颜色
	 * @param position
	 */
	private void setDotColor(int position){
		if (dotContent.getChildCount() > 1) {
			dotContent.setVisibility(View.VISIBLE);
			for (int i = 0; i < dotContent.getChildCount(); i++) {
				if (i == position) {
					dotContent.getChildAt(i).setBackgroundResource(R.drawable.shape_viewpager_dot_selected);
				} else {
					dotContent.getChildAt(i).setBackgroundResource(R.drawable.shape_viewpager_dot_nomal);
				}
			}
		} else {
			dotContent.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		if (postId == CHECKIN) {
			startActivity(new Intent(getActivity(), SignInActivity.class));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_signin:
			
			if (AppBasic.isLogin) {
				if (!AppBasic.isCheckIned) {
					onRequest(CHECKIN, UrlConstant.CHECKIN, HttpMethod.GET, null);
				} else {
					startActivity(new Intent(getActivity(), SignInActivity.class));
				}
			} else {
				startActivity(new Intent(getActivity(), LoginActivity.class));
			}

			break;
		case R.id.btn_popularevent:
			startActivity(new Intent(getActivity(), PopularEventsActivity.class));
			break;
		case R.id.btn_latest:
			startActivity(new Intent(getActivity(), LatestActivity.class));
			break;
		case R.id.btn_notice:
			startActivity(new Intent(getActivity(), HmNoticeActivity.class));
			break;

		default:
			break;
		}

	}

	@Override
	public void onPageScrollStateChanged(int arg0) {}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {}

	@Override
	public void onPageSelected(int position) {
		pos = position;

		setDotColor(position);

		if (position == 0) {
			Intent intent = new Intent("isDrag");
			intent.putExtra("isDrag", true);
			getActivity().sendBroadcast(intent);
		} else {
			Intent intent = new Intent("isDrag");
			intent.putExtra("isDrag", false);
			getActivity().sendBroadcast(intent);
		}
	}

	@Override
	public boolean onTouch(View view, MotionEvent event) {
		Intent intent = new Intent("isDrag");
		switch (event.getAction()) {
		case MotionEvent.ACTION_MOVE:

			break;
		case MotionEvent.ACTION_DOWN:
			intent.putExtra("isDrag", false);
			getActivity().sendBroadcast(intent);
			break;
		case MotionEvent.ACTION_UP:
			if (pos == 0) {
				intent.putExtra("isDrag", true);
			} else {
				intent.putExtra("isDrag", false);
			}
			getActivity().sendBroadcast(intent);
			break;
		default:
			break;
		}
		return false;
	}
}